//
//  AppDelegate.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/6.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        /// 设置应用程序额外信息
        appAdditions()
        
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        
        window?.rootViewController = LJTabbarController()
        window?.makeKeyAndVisible()
        
        /// 加载访客信息
        loadVisitorInfo()
        return true
    }
}

// MARK: - 应用程序额外信息设置
extension AppDelegate {
    
    fileprivate func appAdditions() {
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        /// 用户权限
        applyUserAuthority()
    }
}

extension AppDelegate {
    
    /// 申请用户权限
    fileprivate func applyUserAuthority() {
        if #available(iOS 10.0, *) {    // 10.0以上
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge, .carPlay]) { (isSuccess, error) in
                print("用户权限申请" + (isSuccess ? "成功" : "失败"))
            }
        } else {
            // 10.0以下
            let notifySet = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifySet)
        }
    }
    
    
    fileprivate func loadVisitorInfo() {
        
        DispatchQueue.global().async {
            
            let jsonDoc = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (jsonDoc as NSString).appendingPathComponent("main.json")
            
            /// 先从服务器加载，完成之后保存到沙盒
            let bundlePath =  Bundle.main.path(forResource: "main.json", ofType: nil)
            let jsonData = NSData(contentsOfFile: bundlePath!)
            
            /// 写入磁盘
            if (jsonData?.write(toFile: jsonPath, atomically: true)) == true {
                
                print("写入成功\(jsonDoc)")
            }
        }
    }
}



